/**
 * Created by LeungZ on 2016/10/17.
 */
import logTmp from './form/log.html';
import logCtrl from './form/log.ctrl.js';
import fileTmp from '../../docker/detail/form/file.html';
import fileCtrl from '../../docker/detail/form/file.ctrl.js';
import uploadTmp from './form/upload.html';
import uploadCtrl from './form/upload.ctrl.js';

class Image {
    constructor(list, appSrv, ctgNotification, $timeout, $scope, $uiModal) {
        "ngInject";
        this._appSrv = appSrv;
        this._notification = ctgNotification;
        this._timeout = $timeout;
        this._uiModal = $uiModal;
        this.timer = '';
        this.statusList = [{val: '000', name: '构建中'}, {val: '001', name: '构建成功'}, {val: '002', name: '构建失败'}];

        this.page = {
            currentPage: 1,
            totalItems: 0
        };
        this.filter = {
            name: null,
            ver: null,
            status: null
        };

        if (list) {
            this.table = list.list;
            this.page.totalItems = list.total;
            this.refreshData();
        } else this.table = [];

        $scope.$on('$destroy', ()=> {
            this._timeout.cancel(this.timer);
        });
    }

    search() {
        this.page.currentPage = 1;
        this.getList();
    }

    getList() {
        this._timeout.cancel(this.timer);
        this.table = null;
        this.getData();
    }

    refreshData() {
        for (var i in this.table) {
            if (this.table[i].buildImageState == '000') {
                this.timer = this._timeout(this.getData.bind(this), 5000);
                return;
            }
        }
    }

    getData() {
        this._appSrv.getBuildList({currentPage: this.page.currentPage}, this.filter).then(data=> {
            this.table = data.list;
            this.page.totalItems = data.total;
            this.refreshData();
        }).catch(()=> {
            if (!this.table) {
                this.table = [];
                this.page.totalItems = 0;
            }
            this._notification.error('获取构建数据有误.');
        });
    }

    openUploadForm(){
        this._uiModal.open({
            animation: true,
            templateUrl: uploadTmp,
            controller: uploadCtrl,
            controllerAs: 'vm',
            size: 'md'
        });
    }

    openLogForm(elem) {
        this._uiModal.open({
            animation: true,
            templateUrl: logTmp,
            controller: logCtrl,
            controllerAs: 'vm',
            size: 'lg',
            resolve: {
                buildId: elem.id
            }
        });
    }

    openFileForm(elem) {
        this._uiModal.open({
            animation: true,
            templateUrl: fileTmp,
            controller: fileCtrl,
            controllerAs: 'vm',
            size: 'lg',
            resolve: {
                dockerFile: function () {
                    return elem.dockerfile;
                }
            }
        });
    }
}
export default Image